package com.interview.javabase.algorithm.链表;

/**
 * 面试题 02.08. 环路检测
 * https://leetcode-cn.com/problems/linked-list-cycle-lcci/
 *
 * @author zhangshguang
 * @date 2020/09/21
 */
public class 环路检测 {

    /**
     * 快慢指针
     *
     * @param head
     * @return
     */
    public boolean detectCycle(ListNode head) {

        if (head == null || head.next == null){
            return false;
        }

        /**
         * 一前一后为了不下面校验方便
         */
        ListNode slow = head;
        ListNode fast = head.next;

        //  && fast.next != null 此处需要注意
        while (fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;

            if (slow == fast){
                return true;
            }
        }

        return false;
    }
}
